package com.person.jc.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.jfinal.plugin.activerecord.Record;
import com.person.jc.common.Constants;
import com.person.jc.service.security.TsCodeService;
import com.person.jc.utils.JsonMapper;
import com.person.jc.utils.Utils;
public class SelectTag extends BodyTagSupport {
	
    private static final long serialVersionUID = 1L;

    private String id;//框件id

    private String name;//框件name

    private String sqlname;//属性文件中sql名称

    private String sqlparam;//属性文件中sql参数，多个使用“,”分割

    private String def;//默认项，如果不需要置为false，默认为“请选择”，可自定义

    private String defval;//默认选中项，value值

    private String onchange;//值改变时触发事件，需要在页面添加回调函数，返回newValue,oldValue

    private String style;//自定义框件样式
    
    private String disabled;//禁用时传true，默认false
    
    private String multiple;//是否多选，默认false

    private String separator;//多选时使用的分隔符，默认为“,”
    
    private String editable;//是否可输入，默认false
    
    private String panelHeight;//下拉面板高度，默认“auto”
    
    private String hasDownArrow;//是否显示右侧下拉箭头
    
    private String ifSelect;//true:下拉框（默认）；false:只显示名字

    private String ifTree;//是否展示树状结构
    
    private String width;//组件宽度
    
    private String height;//组件高度
    
    private String ifSearch;//是否为查询条件中下拉框
    
    private String displayText;//查询条件中显示文本
    
    private String onSelect;//选中事件
    
    private String className;//class
    
    private String data;//选择项
    
    private String preData;//在查询内容前追加数据
    
    
    
	public String spellHtml(List<Record> codeList) {
        StringBuffer html = new StringBuffer();
        boolean isTree = false;
        boolean isSearch = false;
        if(Utils.isNotEmpty(ifTree) && !"false".equals(ifTree.toLowerCase()))
            isTree = true;
        if(Utils.isNotEmpty(ifSearch) && !"false".equals(ifSearch.toLowerCase()))
            isSearch = true;
        
        if((Utils.isNotEmpty(ifSelect) && "false".equals(ifSelect.toLowerCase()))){
            if (codeList != null && Utils.isNotEmpty(defval)) {
                for (Record tempMap : codeList) {
                    String key = String.valueOf(tempMap.get(Constants.defSelectKey));
                    String value = String.valueOf(tempMap.get(Constants.defSelectText));
                    if(isTree){
                        String[] keys = key.split(",");
                        key = keys[0];
                    }
                    if (defval != null && defval.equals(key)) {
                        html.append("<input type='text' value='"+value+"' class='wd170' style='width:99%;' disabled>");
                        html.append("<input type = 'hidden' id='"+id+"' name ='"+name+"' value='"+key+"' />");
                        break;
                    }
                }
                if(Utils.isEmpty(html.toString())){
                    html.append(Utils.convertNullToEmpty(def));
                }
            }else{
                html.append(Utils.convertNullToEmpty(def));
            }
        }else{
            String defText = "";
            if (!"false".equals(def)) {
                defText = "--请选择--";
                if(Utils.isNotEmpty(def))
                    defText = def;
            }
            
            if(isSearch){
                if(Utils.isNotEmpty(displayText))
                    displayText += "：";
                else
                    displayText = "";
                
                int colW = 210;
                int leftW = displayText.length() * 14;
                int mLeft = colW - leftW;
                
                html.append("<div class=\"rewrite_select f_l border_left_1\">");
                html.append("<label class=\"left_desc\" style=\"width:"+leftW+"px;\">"+ displayText +"</label>");
                    width = mLeft + "px";
            }
            html.append("<select class=\"normal_select");
            
            if(className != null)
                html.append(" "+ className +"");            
            html.append("\"");
            
            if (id != null) {
                html.append(" id=\""+ id +"\"");
            }
            if (name != null) {
                html.append(" name=\""+ name +"\"");
            }
            
            if (width == null) {
                width = "150px";
            }
            if(!width.endsWith("%") && !width.endsWith("px") && !width.equals("auto"))
                width = width + "px";
            
            html.append(" style=\"width:"+ width +";\"");
            if(Utils.isNotEmpty(disabled))
                html.append(" disabled=\""+ disabled +"\"");
                
            if (onchange != null) {
                html.append(" onchange=\""+onchange+"(this.value)\"");
            }
            
            html.append(">");
            
            if(Utils.isNotEmpty(defText))
                html.append("<option value=\"\">"+ defText +"</option>");            
            
            codeList = Utils.getSelect(codeList, isTree);
            for(Record tempMap:codeList){
                String key = String.valueOf(tempMap.get(Constants.defSelectKey));
                if(isTree){
                    String[] keys = key.split(",");
                    key = keys[0];
                }
                String value = String.valueOf(tempMap.get(Constants.defSelectText));
                html.append(" <option value=\""+key+"\"");
                if(Utils.isNotEmpty(defval) && defval.equals(key))
                    html.append(" selected=\"true\"");
                
                html.append(">"+ value +"</option>");
            }
            
            html.append("</select>");
            if(isSearch){
                html.append("</div>");
            }
        }
        
        return html.toString();
    }
    
    @SuppressWarnings("unchecked")
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            List<Record> mapList = new ArrayList<Record>();
            if(Utils.isNotEmpty(data)){
                if(data.indexOf("{") > -1){//认为json格式
                	JsonMapper json = JsonMapper.nonDefaultMapper();
                	mapList = json.fromJson(data, List.class);
                }else{//数组 格式[a,b,c]，值从1开始
                    if(data.startsWith("[")){
                        data = data.substring(1, data.length() - 1);
                    }
                    int i = 1;
                    for(String text : data.split(",")){
                    	Record rd = new Record();
                    	rd.set(Constants.defSelectKey, i);
                    	rd.set(Constants.defSelectText, text);
                        mapList.add(rd);
                        i++;
                    }
                }
            }else if(Utils.isNotEmpty(sqlname) && !"noSearch".equals(sqlname)){
                if(Utils.isNotEmpty(preData)){
                	JsonMapper json = JsonMapper.nonDefaultMapper();
                	mapList = json.fromJson(preData, List.class);
                }
                
                List<Record> mapList2 = new ArrayList<Record>();
                if("getCodeData".equals(sqlname)){
                	mapList2 = TsCodeService.me.getKindCode(sqlparam);
                }else{
                    mapList2 =  SelectTagDao.me.getExecuteResult(sqlname, sqlparam);
                }
                
                if(mapList2 != null && mapList2.size() > 0){
                	mapList.addAll(mapList2);
                }
            }
            
            out.write(spellHtml(mapList));
        }
        catch (Exception e) {
//            throw new JspException("Error:" + e.getMessage());
            e.printStackTrace();
        }
        return EVAL_BODY_INCLUDE;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSqlname() {
        return sqlname;
    }

    public void setSqlname(String sqlname) {
        this.sqlname = sqlname;
    }

    public String getSqlparam() {
        return sqlparam;
    }

    public void setSqlparam(String sqlparam) {
        this.sqlparam = sqlparam;
    }

    public String getDefault() {
        return def;
    }

    public void setDefault(String def) {
        this.def = def;
    }

    public String getDefval() {
        return defval;
    }

    public void setDefval(String defval) {
        this.defval = defval;
    }

    public String getOnchange() {
        return onchange;
    }

    public void setOnchange(String onchange) {
        this.onchange = onchange;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getDisabled() {
        return disabled;
    }

    public void setDisabled(String disabled) {
        this.disabled = disabled;
    }

    public String getIfSelect() {
        return ifSelect;
    }

    public void setIfSelect(String ifSelect) {
        this.ifSelect = ifSelect;
    }

    public String getDef() {
        return def;
    }

    public void setDef(String def) {
        this.def = def;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getMultiple() {
        return multiple;
    }

    public void setMultiple(String multiple) {
        this.multiple = multiple;
    }

    public String getSeparator() {
        return separator;
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }

    public String getEditable() {
        return editable;
    }

    public void setEditable(String editable) {
        this.editable = editable;
    }

    public String getPanelHeight() {
        return panelHeight;
    }

    public void setPanelHeight(String panelHeight) {
        this.panelHeight = panelHeight;
    }

    public String getHasDownArrow() {
        return hasDownArrow;
    }

    public void setHasDownArrow(String hasDownArrow) {
        this.hasDownArrow = hasDownArrow;
    }

    public String getWidth() {
        return width;
    }

    public void setWidth(String width) {
        this.width = width;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getIfTree() {
        return ifTree;
    }

    public void setIfTree(String ifTree) {
        this.ifTree = ifTree;
    }

    public String getIfSearch() {
        return ifSearch;
    }

    public void setIfSearch(String ifSearch) {
        this.ifSearch = ifSearch;
    }

    public String getDisplayText() {
        return displayText;
    }

    public void setDisplayText(String displayText) {
        this.displayText = displayText;
    }

	public String getOnSelect() {
		return onSelect;
	}

	public void setOnSelect(String onSelect) {
		this.onSelect = onSelect;
	}

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getPreData() {
        return preData;
    }

    public void setPreData(String preData) {
        this.preData = preData;
    }
    
}